package com.huawei.aiservice.filters;

import com.huawei.aiservice.constants.GatewayConstant;
import com.huawei.aiservice.utils.JwtUtil;
import com.huawei.aiservice.utils.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;


@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        if ("/api/gateway/logout".equals(path)) {
            return logOut(response);
        }

        // 检验是否登录，并刷新token
        String token = validateLogin(request);
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

//        ResponseCookie cookie = JwtUtil.getCookie(token, 2 * 60 * 60);
//        response.addCookie(cookie);

        return chain.filter(exchange);
    }

    /**
     * 退出登录
     *
     * @param response 响应信息
     * @return 过滤器链
     */
    public Mono<Void> logOut(ServerHttpResponse response) {
        ResponseCookie cookie = JwtUtil.getCookie("", 0);
        response.addCookie(cookie);
        HashMap<String, String> map = new HashMap<>();
        map.put("result", GatewayConstant.RequestMessage.SUCCESS);
        return ResponseUtil.getUserResponse(response, map);
    }

    /**
     * 验证是否登录
     *
     * @param request 请求
     * @return String 身份令牌
     */
    public String validateLogin(ServerHttpRequest request) {
        String token = JwtUtil.getTokenFromCookie(request);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(token)) {
            token = JwtUtil.verifyToken(token);
        }
        return token;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
